<template>
  <div class="bg-in-stock">
    <el-form ref="orderFormRef" :rules="rules" :model="OrderForm" label-width="120px" inline :disabled="isDetail">
      <h3>基本信息</h3>
      <el-form-item label="仓库" prop="warehouse_id" :rules="rules.warehouse_id">
        <el-select @change="cleanGoodsList" v-model="OrderForm.warehouse_id">
          <el-option v-for="item in warehouseList" :key="item.id" :label="item.name" :value="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="会员" prop="owner_id" :rules="rules.owner_id" v-if="type === 'TO_C'">
        <el-select v-model="OrderForm.owner_id">
          <el-option v-for="item in memberList" :key="item.id" :label="item.name" :value="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="企业" prop="owner_id" :rules="rules.owner_id" v-else>
        <el-select v-model="OrderForm.owner_id">
          <el-option v-for="item in enterpriseList" :key="item.id" :label="item.name" :value="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="下单时间" prop="order_time" :rules="rules.order_time">
        <el-date-picker v-model="OrderForm.order_time" value-format="timestamp" type="datetime" :editable="false" :clearable="false" style="width: 100%"/>
      </el-form-item>
      <el-form-item label="销售经理">
        <el-select v-model="OrderForm.marketing_id">
          <el-option v-for="item in marketingList" :key="item.id" :label="item.real_name" :value="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="支付状态" prop="payment_status" :rules="rules.payment_status">
        <el-select v-model="OrderForm.payment_status">
          <el-option key="NOT_PAY" label="未支付" value="NOT_PAY"/>
          <el-option key="PAY" label="已支付" value="PAY"/>
        </el-select>
      </el-form-item>
      <el-form-item label="支付时间" prop="payment_time" :rules="rules.payment_time" v-if="OrderForm.payment_status === 'PAY'">
        <el-date-picker v-model="OrderForm.payment_time" value-format="timestamp" type="datetime" :editable="false" :clearable="false" style="width: 100%"/>
      </el-form-item>
      <el-form-item label="配送方式" prop="delivery_type" :rules="rules.delivery_type" v-if="type === 'TO_B'">
        <el-select v-model="OrderForm.delivery_type">
          <el-option v-for="item in deliveryTypeList" :key="item.code" :label="item.name" :value="item.code"/>
        </el-select>
      </el-form-item>
      <template v-if="OrderForm.delivery_type === 'express' && type === 'TO_B'">
        <el-form-item label="配送地区" prop="ship_region_id">
          <en-region-picker :api="MixinRegionApi" :default="defaultShipRegion"
                            @changed="(object) => { OrderForm.ship_region_id = object.last_id }" />
        </el-form-item>
        <el-form-item label="配送详细地址" prop="ship_address">
          <el-input v-model="OrderForm.ship_address" ></el-input>
        </el-form-item>
      </template>
      <el-form-item label="自提门店" v-if="OrderForm.delivery_type === 'self_pick'" prop="store_id">
        <el-select v-model="OrderForm.store_id">
          <el-option v-for="item in storeList" :key="item.id" :label="item.store_name" :value="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="订单备注" prop="remark">
        <el-input v-model="OrderForm.remark"  type="textarea" :autosize="{ minRows: 2 }" ></el-input>
      </el-form-item>
      <el-form-item label="附件" prop="attachment" style="width: 500px" v-if="type === 'TO_B'">
        <el-upload multiple :action="MixinUploadApi" :file-list="fileList" v-if="!isDetail"
                   :on-success="(res) => { OrderForm.attachment = res.url }" :limit="1">
          <el-button size="mini" type="primary">上传</el-button>
        </el-upload>
        <a v-if="OrderForm.attachment" :href="OrderForm.attachment" target="_blank"
           style="color:#409EFF;font-size:12px">下载附件</a>
      </el-form-item>

    <div style="margin-bottom: 10px">
      <h3>商品明细</h3>
      <div v-if="!isDetail">
        <el-button class="button" size="mini" type="primary" @click="handleSelectGoods">添加</el-button>

        <el-button class="button" size="mini" @click="handleShowUpdateNum" v-if="!showUpdateNum">
          设置数量
        </el-button>
        <span v-else>
          <el-input style="width: 70px;" @keydown.enter.native="handleConfirmUpdateNum"
                    ref="batchSetNumRef" v-model="batchUpdateNum"></el-input>
          <el-button class="button" size="mini" @click="handleCancelUpdateNum">取消</el-button>
          <el-button class="button" size="mini" type="primary" @click="handleConfirmUpdateNum">确认</el-button>
        </span>

        <el-button class="button" size="mini" @click="handleShowUpdateTaxRate" v-if="!showTaxRate">
          设置税率
        </el-button>
        <span v-else>
          <el-input style="width: 70px;" @keydown.enter.native="handleConfirmUpdateTaxRate" ref="batchSetTaxRateRef"
                    v-model="batchTaxRate"></el-input>
          <el-button class="button" size="mini" @click="handleCancelUpdateTaxRate">取消</el-button>
          <el-button class="button" size="mini" type="primary" @click="handleConfirmUpdateTaxRate">确认</el-button>
        </span>

        <el-button class="button" size="mini" @click="handleShowUpdateDiscountPrice"
                   v-if="!showDiscountPrice">设置优惠金额
        </el-button>
        <span v-else>
          <el-input style="width: 170px;" @keydown.enter.native="handleConfirmUpdateDiscountPrice"
                    ref="batchSetDiscountRef" v-model="batchDiscountPrice">
            <template #prepend>
              <el-select v-model="batchDiscountType" style="width: 100px;">
                <el-option :value="0" label="按百分比"></el-option>
                <el-option :value="1" label="按金额"></el-option>
              </el-select>
            </template>
          </el-input>
          <el-button class="button" size="mini" @click="handleCancelUpdateDiscountPrice">取消</el-button>
          <el-button class="button" size="mini" type="primary" @click="handleConfirmUpdateDiscountPrice">确认</el-button>
        </span>
      </div>
    </div>
    <div style="display:block">
      <el-table :data="OrderForm.item_list" border :cell-style="{ textAlign: 'center' }"
                @selection-change="handleSelectionChange"
                :header-cell-style="{ textAlign: 'center' }" style="width: 95%; ">
        <el-table-column type="selection" width="40" align="center"/>
        <el-table-column label="商品编号">
          <template slot-scope="scope">
            {{ scope.row.product_sn }}
          </template>
        </el-table-column>
        <el-table-column label="商品名称">
          <template slot-scope="scope">
            {{ scope.row.product_name }}
          </template>
        </el-table-column>
        <el-table-column label="规格型号">
          <template slot-scope="scope">
            {{ scope.row.product_specification }}
          </template>
        </el-table-column>
        <el-table-column label="单位">
          <template slot-scope="scope">
            {{ scope.row.product_unit }}
          </template>
        </el-table-column>
        <el-table-column label="剩余库存">
          <template slot-scope="scope">
            {{ scope.row.stock_num }}
          </template>
        </el-table-column>
        <el-table-column label="数量">
          <template slot-scope="scope">
            <el-form-item v-if="!isDetail" :prop="'item_list.'+scope.$index+'.num'" :rules="rules.item_list.num" class="tableFormItem">
              <el-input v-model="scope.row.num" :maxlength="20" :minlength="1"></el-input>
            </el-form-item>
            <span v-else>{{ scope.row.num }}</span>
          </template>
        </el-table-column>
        <el-table-column label="单价">
          <template slot-scope="scope">
            <el-form-item v-if="!isDetail" :prop="'item_list.'+scope.$index+'.price'" :rules="rules.item_list.price" class="tableFormItem">
              <el-input v-model="scope.row.price" :maxlength="20" :minlength="1"></el-input>
            </el-form-item>
            <span v-else>{{ scope.row.price }}</span>
          </template>
        </el-table-column>
        <el-table-column label="金额">
          <template slot-scope="scope">
            {{ scope.row.total_price.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="税率">
          <template slot-scope="scope">
            <el-form-item v-if="!isDetail" :prop="'item_list.'+scope.$index+'.tax_rate'" :rules="rules.item_list.tax_rate" class="tableFormItem">
              <el-input v-model="scope.row.tax_rate" :maxlength="20"></el-input>
            </el-form-item>
            <span v-else>{{ scope.row.tax_rate }}</span>
          </template>
        </el-table-column>
        <el-table-column label="税额">
          <template slot-scope="scope">
            {{ scope.row.tax_price.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="优惠金额">
          <template slot-scope="scope">
            <el-form-item v-if="!isDetail" :prop="'item_list.'+scope.$index+'.discount_price'" :rules="rules.item_list.discount_price" class="tableFormItem">
              <el-input v-model="scope.row.discount_price"></el-input>
            </el-form-item>
            <span v-else>{{ scope.row.discount_price }}</span>
          </template>
        </el-table-column>
        <el-table-column label="合计">
          <template slot-scope="scope">
            {{ scope.row.pay_price.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="备注">
          <template slot-scope="scope">
            <el-input v-if="!isDetail" v-model="scope.row.remark"></el-input>
            <span v-else>{{ scope.row.remark }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" v-if="!isDetail">
          <template slot-scope="scope">
            <el-button size="mini" type="danger"
                       @click="OrderForm.item_list.splice(scope.$index, 1)">删除
            </el-button>
          </template>
        </el-table-column>
        <div slot="append" style="text-align: right;line-height: 50px;margin-right: 20px;font-size: small" v-if="OrderForm.total_price">
          商品金额：{{ OrderForm.total_price.toFixed(2) }} &nbsp;&nbsp;&nbsp;&nbsp;
          税额：{{ OrderForm.tax_price.toFixed(2) }} &nbsp;&nbsp;&nbsp;&nbsp;
          优惠金额：{{ OrderForm.discount_price.toFixed(2) }} &nbsp;&nbsp;&nbsp;&nbsp;
          实付金额：{{ OrderForm.pay_price.toFixed(2) }}
        </div>
      </el-table>
    </div>
    <div class="mx">
      <h3>支付信息</h3>
      <el-button v-if="!isDetail" class="button" size="mini" type="primary" icon="el-icon-circle-plus-outline"
                 @click="handleInsertPayment"></el-button>
    </div>
    <div style="display:block">
      <el-table :data="OrderForm.payment_list" border :cell-style="{ textAlign: 'center' }"
                :header-cell-style="{ textAlign: 'center' }" style="width: 95%; ">
        <el-table-column label="支付方式">
          <template slot-scope="scope">
            <el-form-item v-if="!isDetail" :prop="'payment_list.'+scope.$index+'.collecting_account_id'" :rules="rules.payment_list.collecting_account_id" class="tableFormItem">
              <el-select v-model="scope.row.collecting_account_id">
                <el-option v-for="item in collectingAccountList" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
            <span v-else>{{ scope.row.collecting_account_name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="支付金额">
          <template slot-scope="scope">
            <el-form-item v-if="!isDetail" :prop="'payment_list.'+scope.$index+'.price'" :rules="rules.payment_list.price" class="tableFormItem">
              <el-input v-model="scope.row.price"></el-input>
            </el-form-item>
            <span v-else>{{ scope.row.price }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注">
          <template slot-scope="scope">
            <el-input v-if="!isDetail" v-model="scope.row.remark"></el-input>
            <span v-else>{{ scope.row.remark }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" v-if="!isDetail">
          <template slot-scope="scope">
            <el-button size="mini" type="danger"
                       @click="OrderForm.payment_list.splice(scope.$index, 1)">删除
            </el-button>
          </template>
        </el-table-column>
        <div slot="append" v-if="OrderForm.deposit_price" style="text-align: right;line-height: 50px;margin-right: 20px;font-size: small">
          收取定金：{{ OrderForm.deposit_price.toFixed(2) }} &nbsp;&nbsp;
        </div>
      </el-table>
    </div>
    <div class="footer">
      <el-button type="primary" @click="submitOrderForm" v-if="!isDetail" :loading="formLoading">保存</el-button>
      <el-button type="primary" :disabled="false" @click="handleAudit(true)" v-if="isDetail && checkPermission(['order:audit']) && OrderForm.allowable.audit">审核通过</el-button>
      <el-button type="danger" :disabled="false" @click="handleAudit(false)" v-if="isDetail && checkPermission(['order:audit']) && OrderForm.allowable.audit">审核驳回</el-button>
      <el-button @click="backOrderList()" :disabled="false">返回</el-button>
    </div>
    </el-form>
  </div>
</template>

<script>
import {mapGetters} from 'vuex'
import * as API_Order from '@/api/order'
import * as API_BasicSetting from '@/api/basicSetting'
import * as API_Member from '@/api/member'
import * as API_Enterprise from '@/api/enterprise'
import * as API_CollectingAccount from '@/api/collectingAccount'
import { RegExp } from '~/ui-utils'

const initOrderForm = {
  item_list: [],
  payment_list: [],
  tax_price: 0,
  total_price: 0,
  discount_price: 0,
  pay_price: 0,
  deposit_price: 0,
  delivery_type: 'express',
  payment_status: 'NOT_PAY'
}

export default {
  name: 'orderAdd',
  data() {
    return {
      warehouseList: [], // 仓库列表
      memberList: [], // 会员列表
      enterpriseList: [], // 企业列表
      marketingList: [], // 销售经理列表
      storeList: [], // 门店列表
      collectingAccountList: [], // 支付方式列表
      fileList: [],
      deliveryTypeList: [
        {
          code: 'express',
          name: '快递配送'
        },
        {
          code: 'self_pick',
          name: '门店自提'
        }
      ],
      id: '',
      // 订单类型
      type: '',
      /** 订单表单*/
      OrderForm: {},
      defaultShipRegion: [],
      formLoading: false,
      isDetail: undefined,
      multipleSelection: [], // 勾选的商品
      batchUpdateNum: 0, // 批量设置的数量
      showUpdateNum: false, // 是否显示数量设置
      batchDiscountType: 0, // 批量设置的类型 0按比例 1按金额
      batchDiscountPrice: 0, // 批量设置的优惠比例或金额
      showDiscountPrice: false, // 是否显示优惠金额设置
      batchTaxRate: 0, // 批量设置的税率
      showTaxRate: false, // 是否显示税率设置
      rules: {
        warehouse_id: [
          this.MixinRequired('请选择仓库', 'change')
        ],
        owner_id: [
          this.MixinRequired('请选择用户', 'change')
        ],
        order_time: [
          this.MixinRequired('下单时间不能为空', 'change')
        ],
        payment_status: [
          this.MixinRequired('支付状态不能为空', 'change')
        ],
        payment_time: [
          this.MixinRequired('支付时间不能为空', 'change')
        ],
        delivery_type: [
          this.MixinRequired('请选择配送方式', 'change')
        ],
        ship_region_id: [this.MixinRequired('请选择配送地区', 'change')],
        ship_address: [this.MixinRequired('请输入配送详细地址', 'change')],
        store_id: [this.MixinRequired('请选择自提门店', 'change')],
        item_list: {
          num: [
            this.MixinRequired('数量不能为空', 'change'),
            {
              validator: (rule, value, callback) => {
                if (value && !RegExp.integer.test(value)) {
                  callback(new Error('请输入正整数'))
                } else {
                  callback()
                }
              }
            }
          ],
          tax_rate: [
            this.MixinRequired('税率不能为空', 'change'),
            {
              validator: (rule, value, callback) => {
                if (value && !RegExp.money.test(value)) {
                  callback(new Error('请输入正确的税率'))
                } else {
                  callback()
                }
              },
              trigger: 'blur'
            }
          ],
          price: [
            this.MixinRequired('单价不能为空', 'change'),
            {
              validator: (rule, value, callback) => {
                if (value && !RegExp.money.test(value)) {
                  callback(new Error('请输入正确的价格'))
                } else {
                  callback()
                }
              },
              trigger: 'blur'
            }
          ],
          discount_price: [
            this.MixinRequired('优惠金额不能为空', 'change'),
            {
              validator: (rule, value, callback) => {
                if (value && !RegExp.money.test(value)) {
                  callback(new Error('请输入正确的金额'))
                } else {
                  callback()
                }
              },
              trigger: 'blur'
            }
          ]
        },
        payment_list: {
          collecting_account_id: [
            this.MixinRequired('请选择支付方式', 'change')
          ],
          price: [
            this.MixinRequired('支付金额不能为空', 'change'),
            {
              validator: (rule, value, callback) => {
                if (value && !RegExp.money.test(value)) {
                  callback(new Error('请输入正确的金额'))
                } else {
                  callback()
                }
              },
              trigger: 'blur'
            },
            {
              validator: (rule, value, callback) => {
                if (value && value * 1 <= 0) {
                  callback(new Error('支付金额必须大于0'))
                } else {
                  callback()
                }
              },
              trigger: 'blur'
            }
          ]
        }
      }
    }
  },
  computed: {
    ...mapGetters(['user'])
  },
  mounted() {
    this.GET_WarehouseList()
    this.GET_MemberList()
    this.GET_EnterpriseList()
    this.GET_MarketingList()
    this.GET_StoreList()
    this.GET_CollectingAccountList()
  },
  methods: {
    /** 初始化 */
    init() {
      const { id } = this.$route.params
      this.type = this.$route.query.type
      if (id) {
        this.id = id
        this.GET_OrderDetail()
      } else {
        this.OrderForm = this.MixinClone(initOrderForm)
        this.$set(this.OrderForm, 'order_time', new Date().getTime())
        this.$nextTick(() => {
          this.$refs.orderFormRef.clearValidate()
        })
      }
      this.isDetail = this.$route.name === 'orderDetail'
    },
    /** 清除已选商品明细 */
    cleanGoodsList() {
      // 切换仓库需要清除已选对应仓库下的商品数据
      this.$set(this.OrderForm, 'item_list', [])
    },
    /** 获取会员列表 */
    GET_MemberList() {
      API_Member.getMemberList({
        page_no: 1,
        page_size: -1,
        disable_flag: false
      }).then(response => {
        this.memberList = response.data
      })
    },
    /** 获取企业列表 */
    GET_EnterpriseList() {
      API_Enterprise.getList({
        page_no: 1,
        page_size: -1
      }).then(response => {
        this.enterpriseList = response.data
      })
    },
    /** 获取销售经理列表 */
    GET_MarketingList() {
      API_BasicSetting.getMarketingManagerList({
        page_no: 1,
        page_size: -1,
        disable_flag: 0
      }).then(response => {
        this.marketingList = response.data
      })
    },
    /** 获取自提门店列表 */
    GET_StoreList() {
      API_BasicSetting.getBranches({
        page_no: 1,
        page_size: -1
      }).then(response => {
        this.storeList = response.data
      })
    },
    /** 获取支付方式列表 */
    GET_CollectingAccountList() {
      API_CollectingAccount.getList({
        page_no: 1,
        page_size: -1,
        enable_flag: true
      }).then(response => {
        this.collectingAccountList = response.data
      })
    },
    // 选择批次商品
    async handleSelectGoods() {
      if (!this.OrderForm.warehouse_id) {
        this.$message.error('请先选择仓库！')
        return
      }

      if (this.type === 'TO_C') {
        const goodsData = await this.$EnwarehouseEntryBatch({
          goodsApi: 'admin/erp/warehouseEntryBatch',
          warehouseList: [],
          selectedIds: this.OrderForm.item_list.map(item => item.product_id),
          purchasePlanApiParams: { warehouse_id: this.OrderForm.warehouse_id, query_product: true },
          showWarehouseSearch: false
        })
        this.OrderForm.item_list = goodsData.purchasePlans.map(item => {
          // 初始化字段，和订单的item字段名保持一致
          item.batch_id = item.id
          delete item.id
          item.stock_num = item.remain_num
          if (item.product) {
            item.price = item.product.retail_price
            item.tax_rate = item.product.tax_rate
          } else {
            item.price = item.entry_price
            item.tax_rate = 0
          }
          item.num = 1
          item.discount_price = 0
          // 原价（总）
          item.total_price = 0
          // 税额（总）
          item.tax_price = 0
          // 合计
          item.pay_price = 0

          return item
        })
      } else {
        const goodsData = await this.$EnPickerGoods({
          goodsApi: '/admin/erp/product',
          selectedIds: this.OrderForm.item_list.map(item => item.product_id),
          goodsApiParams: { warehouse_id: this.OrderForm.warehouse_id },
          disableSelected: false
        })
        this.OrderForm.item_list = goodsData.map(item => {
          // 初始化字段，和订单的item字段名保持一致
          item.product_id = item.id
          item.product_name = item.name
          item.product_sn = item.sn
          item.product_specification = item.specification
          item.product_unit = item.unit
          item.num = 1
          item.discount_price = 0
          // 原价（总）
          item.total_price = 0
          // 税额（总）
          item.tax_price = 0
          // 合计
          item.pay_price = 0

          return item
        })
      }
    },
    /** 添加支付方式 */
    handleInsertPayment() {
      const defaultCollectingAccount = this.collectingAccountList.findLast(item => item.default_flag === true)
      this.OrderForm.payment_list.push({
        collecting_account_id: defaultCollectingAccount ? defaultCollectingAccount.id : null
      })
    },
    /** table单选框事件 */
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    /** 显示数量设置 */
    handleShowUpdateNum() {
      if (this.multipleSelection.length === 0) {
        this.$message.error('请先勾选商品')
        return
      }
      this.showUpdateNum = true
      this.batchUpdateNum = 1
      this.$nextTick(() => {
        this.$refs.batchSetNumRef.focus()
      })
    },
    /** 取消数量设置 */
    handleCancelUpdateNum() {
      this.showUpdateNum = false
    },
    /** 确认设置数量 */
    handleConfirmUpdateNum() {
      this.showUpdateNum = false
      for (let i = 0; i < this.multipleSelection.length; i++) {
        this.multipleSelection[i].num = this.batchUpdateNum
      }
    },
    /** 显示优惠金额设置 */
    handleShowUpdateDiscountPrice() {
      if (this.multipleSelection.length === 0) {
        this.$message.error('请先勾选商品')
        return
      }
      this.showDiscountPrice = true
      this.batchDiscountPrice = 0
      this.$nextTick(() => {
        this.$refs.batchSetDiscountRef.focus()
      })
    },
    /** 取消优惠金额设置 */
    handleCancelUpdateDiscountPrice() {
      this.showDiscountPrice = false
    },
    /** 确认设置优惠金额 */
    handleConfirmUpdateDiscountPrice() {
      this.showDiscountPrice = false
      for (let i = 0; i < this.multipleSelection.length; i++) {
        const item = this.multipleSelection[i]
        if (this.batchDiscountType === 0) {
          // 按比例
          item.discount_price = item.total_price * this.batchDiscountPrice * 0.01
        } else {
          // 按金额
          item.discount_price = this.batchDiscountPrice
        }
      }
    },
    /** 显示税率设置 */
    handleShowUpdateTaxRate() {
      if (this.multipleSelection.length === 0) {
        this.$message.error('请先勾选商品')
        return
      }
      this.showTaxRate = true
      this.batchTaxRate = 0
      this.$nextTick(() => {
        this.$refs.batchSetTaxRateRef.focus()
      })
    },
    /** 取消税率设置 */
    handleCancelUpdateTaxRate() {
      this.showTaxRate = false
    },
    /** 确认设置税率 */
    handleConfirmUpdateTaxRate() {
      this.showTaxRate = false
      if (this.batchTaxRate != null) {
        for (let i = 0; i < this.multipleSelection.length; i++) {
          this.multipleSelection[i].tax_rate = this.batchTaxRate
        }
      }
    },
    async submitOrderForm() {
      // 校验商品明细数据
      const valid = await this.$refs.orderFormRef.validate().catch(err => err)
      if (valid !== true) {
        this.$message.error('表单数据输入有误，请检查！')
        return
      }
      const {id} = this.OrderForm
      const params = this.MixinClone(this.OrderForm)
      params.order_time = Math.floor(params.order_time / 1000)
      params.payment_time = Math.floor(params.payment_time / 1000)
      params.type = this.type
      this.formLoading = true
      params.tax_price = params.tax_price.toFixed(2)
      params.pay_price = params.pay_price.toFixed(2)
      if (id) {
        API_Order.editOrder(id, params).then(response => {
          this.$message.success('修改成功！')
          this.backOrderList()
        }).finally(() => { this.formLoading = false })
      } else {
        API_Order.addOrder(params).then(() => {
          this.$message.success('添加成功！')
          this.backOrderList()
        }).finally(() => { this.formLoading = false })
      }
    },
    /** 获取仓库 */
    GET_WarehouseList() {
      API_BasicSetting.getWarehouseListAll({}).then(response => {
        this.warehouseList = response
      })
    },
    /** 审核 */
    async handleAudit(isPass, remark) {
      // 二次确认
      const text = isPass ? '审核通过' : '审核驳回'
      await this.$confirm(`确认要${text}吗?`, '提示')
      await API_Order.audit(this.id, isPass, remark)
      this.$message.success('审核成功！')
      this.backOrderList()
    },
    /** 返回订单列表 */
    backOrderList() {
      const {callback} = this.$route.params
      if (typeof callback === 'function') callback()
      this.$store.dispatch('delCurrentViews', {
        view: this.$route,
        $router: this.$router
      })
      this.$router.push({name: this.type === 'TO_C' ? 'retailOrder' : 'order'})
    },
    /** 获取订单详情 */
    GET_OrderDetail() {
      API_Order.getOrderDetail(this.id).then(response => {
        this.type = response.type
        this.OrderForm = response
        this.fileList = response.attachment ? [{name: '附件', url: response.attachment}] : []
        this.OrderForm.order_time = Math.floor(this.OrderForm.order_time * 1000)
        this.defaultShipRegion = response.ship_region_ids
        this.OrderForm.ship_region_id = response.ship_region_ids[3] === '0' ? response.ship_region_ids[2] : response.ship_region_ids[3]
        if (this.OrderForm.payment_time) {
          this.OrderForm.payment_time = Math.floor(this.OrderForm.payment_time * 1000)
        }
      })
    }
  },
  watch: {
    'OrderForm.item_list': {
      deep: true,
      handler(newVal) {
        newVal.forEach(item => {
          // 原价（总）
          item.total_price = item.price * item.num
          // 税额（总）
          item.tax_price = item.total_price * item.tax_rate * 0.01
          // 合计
          item.pay_price = item.total_price + item.tax_price - item.discount_price
        })
        this.OrderForm.total_price = newVal.reduce((sum, item) => sum + item.total_price, 0)
        this.OrderForm.discount_price = newVal.reduce((sum, item) => sum + item.discount_price * 1, 0)
        this.OrderForm.pay_price = newVal.reduce((sum, item) => sum + item.pay_price, 0)
        this.OrderForm.tax_price = newVal.reduce((sum, item) => sum + item.tax_price, 0)
      }
    },
    'OrderForm.payment_list': {
      deep: true,
      handler(newVal) {
        this.OrderForm.deposit_price = newVal.reduce((sum, item) => sum + item.price * 1, 0)
      }
    },
    $route: {
      immediate: true,
      handler(newVal) {
        if (newVal.name === 'orderAdd' || newVal.name === 'orderEdit' || newVal.name === 'orderDetail') {
          this.init()
        }
      }
    },
    'OrderForm.payment_status': {
      handler(newVal) {
        if (newVal === 'PAY' && !this.OrderForm.payment_time) {
          this.OrderForm.payment_time = new Date().getTime()
        }
      }
    }
  }
}
</script>

<style type="text/scss" lang="scss" scoped>
/** 底部步骤 */
.footer {
  width: 95%;
  padding: 10px;
  bottom: 0px;
  text-align: center;
  z-index: 999;
}

.mx {
  display: flex;
  align-items: center;

  .button {
    margin-left: 10px;
  }
}

.bg-in-stock {
  background-color: #fff;
  margin: 10px;
  padding: 25px;
}

/deep/ {
  .el-input--suffix .el-input__inner {
    padding-right: 10px;
  }

  .error-input {
    .el-input__inner {
      border: 1px solid red;
    }
  }
}

/deep/ .el-form-item {
  width: 350px;
}

/** 表格中输入框样式 */
.tableFormItem {
  width: 100%;
  margin-bottom: 0;
}

/** 输入框错误提示样式 */
/deep/ .el-form-item__error{
  position: relative;
}
/** date-picker宽度和其他输入框保持一致 */
/deep/ .el-date-editor {
  .el-input__inner{
    padding-inline-start: 15px
  }
  .el-input__prefix{
    display: none;
  }
}
</style>
